<template>
  <van-form ref="createDelegationInputVO" label-width="85px" label-align="left" :scroll-to-error="true">
    <van-field
      label="团体标志"
      name="logo"
      readonly
      clickable
      required
      input-align="right"
      right-icon="arrow"
      style="line-height: 50px;"
      @click="openChangeLogo"
    >
      <template #input>
        <van-image
          round
          width="50"
          height="50"
          :src="getStaticFileUrl(createDelegationInputVO.imagePath)"
          @click="imagePreview(createDelegationInputVO.imagePath)"
        />
      </template>
    </van-field>
    <van-field
      v-model.trim="createDelegationInputVO.name"
      :readonly="isCheckMode('name')"
      label="团体名称"
      required
      name="name"
      placeholder="请输入团体名称"
      :rules="createDelegationInputVO_Rules.name"
    />
    <van-field
      v-model.trim="createDelegationInputVO.shortName"
      :readonly="isCheckMode('shortName')"
      label="团体简称"
      name="shortName"
      required
      placeholder="请输入团体简称"
      :rules="createDelegationInputVO_Rules.shortName"
    />
    <van-field
      :value="delegationTypeForCheck"
      readonly
      :clickable="!isCheckMode('delegationTypeCode')"
      right-icon="arrow"
      label="团体类型"
      required
      name="delegationTypeCode"
      placeholder="请选择团体类型"
      :rules="createDelegationInputVO_Rules.delegationTypeCode"
      @click="openSelectBox('delegationTypeCode')"
    />
    <van-field
      readonly
      :clickable="!isCheckMode('provinceCode')"
      name="provinceCode"
      label="所在地区"
      required
      placeholder="所在地区"
      right-icon="arrow"
      :value="addressDataForCheck"
      :rules="createDelegationInputVO_Rules.provinceCode"
      @click="openAreaBox()"
    />
    <van-field
      v-model.trim="createDelegationInputVO.address"
      :readonly="isCheckMode('address')"
      rows="1"
      autosize
      label="详细地址"
      type="textarea"
      required
      name="address"
      placeholder="请输入详细地址"
    />
    <van-field
      v-model.trim="createDelegationInputVO.contactPerson"
      :readonly="isCheckMode('contactPerson')"
      label="联系人"
      required
      name="contactPerson"
      placeholder="请输入联系人"
      :rules="createDelegationInputVO_Rules.contactPerson"
    />
    <van-field
      v-model.trim="createDelegationInputVO.phoneNumber"
      :readonly="isCheckMode('phoneNumber')"
      label="联系方式"
      required
      name="phoneNumber"
      placeholder="请输入联系方式"
      :rules="createDelegationInputVO_Rules.phoneNumber"
    />
    <van-field
      v-model.trim="createDelegationInputVO.ctkCode"
      label="中跆协会员号"
      name="ctkCode"
      placeholder="请输入中跆协会员号"
    />
    <van-field
      v-model.trim="createDelegationInputVO.ptkCode"
      label="省跆协会员号"
      name="ptkCode"
      placeholder="请输入省跆协会员号"
    />
    <van-field
      label="机构认证"
      readonly
      clickable
      input-align="right"
      right-icon="arrow"
      @click="openDelegationImgDialog"
    >
      <template #input>
        <!-- 机构营业执照 -->
        <van-image
          v-if="createDelegationInputVO.licenseImage"
          width="48"
          height="30"
          class="gl_mr_5"
          :src="getStaticFileUrl(createDelegationInputVO.licenseImage)"
          @click="imagePreview(teamInfo.licenseImage)"
        />
        <!-- 机构法人证件照正面 -->
        <van-image
          v-if="createDelegationInputVO.idCardImage"
          width="48"
          height="30"
          class="gl_mr_5"
          :src="getStaticFileUrl(createDelegationInputVO.idCardImage)"
          @click="imagePreview(teamInfo.idCardImage)"
        />
        <!-- 机构法人证件照反面 -->
        <van-image
          v-if="createDelegationInputVO.idCardBackImage"
          width="48"
          height="30"
          class="gl_mr_5"
          :src="getStaticFileUrl(createDelegationInputVO.idCardBackImage)"
          @click="imagePreview(teamInfo.idCardBackImage)"
        />
      </template>
    </van-field>
    <popup-select
      ref="popupSelect"
      :select-data="selectData"
      :default-code="selectDefaultCode"
      :value-key="valueKey"
      @onConfirm="confirmSelectBox"
    />
    <popup-area ref="popupArea" :default-area="defaultArea" @onConfirm="confirmAreaBox" />
    <!-- 头像上传 -->
    <van-popup
      v-model="logoDialog"
      get-container="#app"
      position="right"
      :style="{ width: '100%', height: '100%' }"
    >
      <van-nav-bar>
        <template #left>
          <span @click="logoDialog = false">返回</span>
        </template>
      </van-nav-bar>
      <div class="upload_logo" align="center">
        <upload-file
          ref="logo"
          :action="baseUrl + '/api/upload/image'"
          accept=".jpg,.png,.jpeg"
          class-name="logo"
          :file-url="getStaticFileUrl(createDelegationInputVO.imagePath)"
          @uploadSuccess="uploadSuccessLogo"
        >
          <span slot="uploadName" style="font-size: 14px;">点击上传头像</span>
        </upload-file>
      </div>
    </van-popup>
    <!-- 机构认证 - 机构营业执照、机构法人证件照正面、机构法人证件照反面 -->
    <van-popup
      v-model="delegationImgDialog"
      get-container="#app"
      position="right"
      :style="{ width: '100%', height: '100%' }"
    >
      <van-nav-bar>
        <template #left>
          <span @click="delegationImgDialog = false">返回</span>
        </template>
      </van-nav-bar>
      <div class="gl_my_20" align="center">
        <upload-file
          ref="licenseImage"
          :action="baseUrl + '/api/upload/image'"
          accept=".jpg,.png,.jpeg"
          class-name="id_card"
          :file-url="getStaticFileUrl(createDelegationInputVO.licenseImage, 'licenseImage')"
          @uploadSuccess="uploadSuccessLicenseImage"
        >
          <span slot="uploadName" style="font-size: 14px;">点击上传机构营业执照</span>
        </upload-file>
      </div>
      <div class="gl_my_20" align="center">
        <upload-file
          ref="idCardImage"
          :action="baseUrl + '/api/upload/image'"
          accept=".jpg,.png,.jpeg"
          class-name="id_card"
          :file-url="getStaticFileUrl(createDelegationInputVO.idCardImage, 'idCardImage')"
          @uploadSuccess="uploadSuccessIdCardImage"
        >
          <span slot="uploadName" style="font-size: 14px;">点击上传机构法人证件照正面</span>
        </upload-file>
      </div>
      <div class="gl_my_20" align="center">
        <upload-file
          ref="idCardBackImage"
          :action="baseUrl + '/api/upload/image'"
          accept=".jpg,.png,.jpeg"
          class-name="id_card"
          :file-url="getStaticFileUrl(createDelegationInputVO.idCardBackImage, 'idCardBackImage')"
          @uploadSuccess="uploadSuccessIdCardBackImage"
        >
          <span slot="uploadName" style="font-size: 14px;">点击上传机构法人证件照反面</span>
        </upload-file>
      </div>
    </van-popup>
  </van-form>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import {
  SiSTKWEventsManagementCreateDelegationInput
} from '@/lib/form/game/swaggerForm';
import { CreateDelegationInput_Rules } from '@/lib/validate/mobile/myCenter';
import PopupSelect from '@/viewMobile/components/PopupSelect';
import PopupArea from '@/viewMobile/components/PopupArea';
import UploadFile from '@/viewMobile/components/UploadFile/index';
import { deepCopy, CopyData } from '@/lib';
export default {
  components: {
    PopupSelect,
    PopupArea,
    UploadFile
  },
  props: {
    // 传入的团体信息数据
    teamData: {
      type: Object,
      default() {
        return {};
      }
    },
    isShowCode: {
      type: Boolean,
      default: false
    },
    // 是否显示证件照正反面图片上传
    isShowIdCardImage: {
      type: Boolean,
      default: true
    },
    // 是否为查看模式，查看模式将把预设好的字段变为不可编辑状态
    isCheck: {
      type: Boolean,
      default: false
    },
    // 默认的查看模式以原型为基准：包括 name, nationality, nation, idCardTypeCode, idCardNumber, genderCode, birthDate, addressData
    isDefaultCheck: {
      type: Boolean,
      default: false
    },
    // 查看模式字段集合，由调用组件传值决定，示例：['name']
    checkList: {
      type: Array,
      default() {
        return [];
      }
    },
    organizationUnitsTypes: {
      type: Array,
      default () {
        return [];
      }
    }
  },
  data() {
    return {
      baseUrl: WEB_CONFIG.VUE_APP_STATIC_FILE_RUL,
      createDelegationInputVO: new SiSTKWEventsManagementCreateDelegationInput(),
      createDelegationInputVO_Rules: new CreateDelegationInput_Rules(),
      createDelegationInputDTO: {},
      // 选择器
      selectData: [],
      selectDefaultCode: '',
      valueKey: 'value',
      defaultArea: [],
      logoDialog: false,
      delegationImgDialog: false
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      cache: state => state.dict.cache
    }),
    // 显示为只可查看字段的map
    checkListMap () {
      if (this.isDefaultCheck) {
        return {
          name: true,
          shortName: true,
          delegationTypeCode: true,
          addressData: true
        };
      } else {
        const _map = {};
        this.checkList.forEach(item => {
          _map[item] = true;
        });
        return _map;
      }
    },
    // 根据所在地区Code找到对应name
    addressDataForCheck () {
      const _provinceCode = this.createDelegationInputVO.provinceCode;
      const _cityCode = this.createDelegationInputVO.cityCode;
      const _countyCode = this.createDelegationInputVO.countyCode;
      let _provinceData;
      let _cityData;
      let _countyData;
      if (_provinceCode && this.cache.district) {
        _provinceData = this.cache.district.find(item => item.code === _provinceCode);
      }
      if (_cityCode && _provinceData) {
        _cityData = _provinceData.children.find(item => item.code === _cityCode);
      }
      if (_countyCode && _cityData) {
        _countyData = _cityData.children.find(item => item.code === _countyCode);
      }
      return `${_provinceData ? _provinceData.name : ''} ${_cityData ? _cityData.name : ''} ${_countyData ? _countyData.name : ''}`;
    },
    // 根据团队类型找到对应name
    delegationTypeForCheck () {
      const _findData = this.organizationUnitsTypes.find(item => item.code === this.createDelegationInputVO.delegationTypeCode);
      return _findData ? _findData.value : '';
    }
  },
  watch: {
    teamData: {
      immediate: true,
      deep: true,
      handler(val) {
        if (val) {
          this.init(val);
        }
      }
    }
  },
  created() {
    this.getDict();
    this.init();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    init() {
      this.createDelegationInputVO = new SiSTKWEventsManagementCreateDelegationInput();
      this.createDelegationInputDTO = deepCopy(this.teamData);
      CopyData(this.createDelegationInputDTO, this.createDelegationInputVO);
      // 处理所在地区显示
      this.createDelegationInputDTO.addressData = (this.createDelegationInputVO.provinceCode || '') + (this.createDelegationInputVO.cityCode || '') + (this.createDelegationInputVO.countyCode || '');
    },
    getcreateDelegationInputVO() {
      return new Promise((resolve, reject) => {
        this.$refs.createDelegationInputVO.validate().then(() => {
          resolve(this.createDelegationInputVO);
        });
      });
    },
    // 字段是否只可查看处理函数
    isCheckMode (key) {
      // 如果 isCheck 存在则以 isCheck 为准
      if (this.isCheck) {
        return this.isCheck;
      } else {
        return (key in this.checkListMap);
      }
    },
    // 根据code在相应字典中寻找数据
    findDictDataByCode (dictKey, code) {
      const _dict = this.dict[dictKey];
      if (_dict) {
        return _dict.find(item => item.code === code) || {};
      } else {
        console.log('findDictDataByCode -> findDictDataByCode: ' + dictKey + ', 未找到字典数据.');
        return {};
      }
    },
    /* ===== select 选择器相关 ===== */
    openSelectBox(code) {
      if (this.isCheckMode(code)) return;
      // 解决某种情况下弹出框非本系统操作关闭之后无法打开
      this.$refs.popupSelect.close();
      this.selectBoxCode = code;
      this.valueKey = 'value';
      this.selectDefaultCode = this.createDelegationInputVO.delegationTypeCode;
      switch (code) {
        // 机构类型
        case 'delegationTypeCode':
          this.valueKey = 'value';
          this.selectData = this.dict ? this.dict.delegationType : [];
          break;
        default:
          this.selectData = this.dict ? this.dict[code] : [];
          break;
      }
      this.$refs.popupSelect.open();
    },
    confirmSelectBox(value) {
      switch (this.selectBoxCode) {
        default:
          this.$set(this.createDelegationInputVO, this.selectBoxCode, value.code);
          break;
      }
    },
    openAreaBox() {
      if (this.isCheckMode('provinceCode')) return;
      const provinceCode = this.createDelegationInputVO.provinceCode;
      const cityCode = this.createDelegationInputVO.cityCode;
      const countyCode = this.createDelegationInputVO.countyCode;
      this.defaultArea = [provinceCode, cityCode, countyCode];
      this.$refs.popupArea.open();
    },
    confirmAreaBox(value) {
      this.createDelegationInputVO.provinceCode = value[0] && value[0].code;
      this.createDelegationInputVO.cityCode = value[1] && value[1].code;
      this.createDelegationInputVO.countyCode = value[2] && value[2].code;
      this.$refs.popupArea.close();
    },
    uploadSuccessLogo(response) {
      this.$set(this.createDelegationInputVO, 'imagePath', response.tempUrl);
    },
    // 打开修改头像框
    openChangeLogo() {
      this.logoDialog = true;
    },
    // 打开机构认证弹出框
    openDelegationImgDialog() {
      this.delegationImgDialog = true;
    },
    uploadSuccessLicenseImage(response) {
      this.$set(this.createDelegationInputVO, 'licenseImage', response.tempUrl);
    },
    uploadSuccessIdCardImage(response) {
      this.$set(this.createDelegationInputVO, 'idCardImage', response.tempUrl);
    },
    uploadSuccessIdCardBackImage(response) {
      this.$set(this.createDelegationInputVO, 'idCardBackImage', response.tempUrl);
    },
    // 图片预览
    imagePreview(relativeUrl) {
      this.$imagePreview([this.getStaticFileUrl(relativeUrl)]);
      event.stopPropagation();
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl, code) {
      if (relativeUrl) {
        return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
      } else {
        return code ? '' : require('@/assets/images/face_default.png');
      }
    }
  }
};
</script>
<style>
.upload_logo {
  position: absolute;
  top: 40%;
  left: 50%;
  width: 100%;
  height: 200px;
  transform: translate(-50%, -50%);
}
</style>
